function TLModelmanagerDlg(action, varargin)

% TL_MODELMANAGER_DLG manages user interface for TargetLink model manager block
%
% SYNTAX dlgdata = ...
%           TLModelmanagerDlg('create', model, options);
%   creates all controls of dialog
%
%   INPUT ARGUMENTS
%   model       model name
%   options     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -
%
% SYNTAX TLModelmanagerDlg('Manage', dlgfig, dlgdata, pageAction);
%   manage all actions of dialog
%
%   INPUT ARGUMENTS
%   dlgfig      handle of dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit
% $RCSfile: TLModelmanagerDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_UtilityBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.2 $
% $Date: 2011/08/19 07:44:54MESZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


if nargin == 0;
    % set default action
    action = 'create';
end
if nargin > 1;
    model = varargin{1};
    % make sure, that current model is open
    if ~ds_isa(model, 'slblock')
        model = tl_get_current_model;
    end
else
    % set default model
    [model, msg] = tl_get_current_model;
    if isempty(model)
        ds_error_msg(msg);
        return;
    end
end

switch action
    case 'create'
        dlgfigs = ds_find_dialogs('TargetLink Standalone Model Manager Dialog');
        for k = 2 : numel(dlgfigs)
            delete(dlgfigs(k));
        end
        if ~isempty(dlgfigs)
            % dialog is still open, get current model
            figure(dlgfigs(1));
            dlgdata = get(dlgfigs(1),'UserData');
            if isempty(model)
                dlgdata.options.model = '';
            else
                dlgdata.options.model = getfullname(bdroot(model));
            end
            FcnUpdate(dlgfigs(1),dlgdata);
            return
        end
        if nargin > 2
            options = varargin{2};
        else
            options = FcnGetDefaultData;
        end
        options.model = getfullname(bdroot(model));
        FcnCreate(options);
        
    case 'manage'
        dlgfig = varargin{1};
        dlgdata = get(dlgfig,'UserData');
        FcnManageControls(dlgfig, dlgdata, varargin{2});
        
    otherwise
        error(['Invalid action ''' action '''']);
end


%-------------------------------------------------------------------------------
% FcnCtrlPositions calculates positions of blockspecific controls of parameters page.
%   Positions are calculated from the bottom left of the fig to avoid dependencies on figure size.
%
% INPUT ARGUMENTS
%   commonGeom      common geometry like text height, ...
%
% OUTPUT ARGUMENTS
%   ctrlPos         position of the controls
%   sheetDims       total sheetDims of all controls ([width height])
%-------------------------------------------------------------------------------
function [sheetDims,ctrlPos] = FcnCtrlPositions(commonGeom)

strings_and_styles = { ...
    repmat('m',1,50),                                           'edit'; ...
    '  . . .  '                                                 'pushbutton'; ...
    'Destination block for selected TargetLink subsystem',      'text'; ...
    'Create definitions for extern global interface variables', 'checkbox'; ...
    'Generate TRC file, show hierachy of ',                     'checkbox'; ...
    repmat('m',1,25),                                           'popupmenu'; ...
    '  Build  '                                                 'pushbutton'};

[parametersEditSize, ...
    browseButtonSize, ...
    parametersLabelSize, ...
    parametersCheckboxSize, ...
    generateTRCCheckboxSize, ...
    parametersPopupSize, ...
    buildButtonSize] = ...
    ds_get_uicontrol_sizes(commonGeom,strings_and_styles);

widths = parametersEditSize(1);
[col,colWidth,colDelta,rowDelta] = ds_get_gui_columns(widths,commonGeom);

parametersGroupboxWidth = col(end) + ...
    colWidth(end) + ...
    commonGeom.frameSideEdgeBuffer;
parametersGroupboxHeight = ...
    commonGeom.frameTopEdgeBuffer + ...
    18 * rowDelta + ...
    20 * commonGeom.editHeight + ...
    commonGeom.frameBottomEdgeBuffer;

cx = commonGeom.figSideEdgeBuffer + commonGeom.sheetSideEdgeBuffer;
cy = commonGeom.bottomSheetOffset + ...
    commonGeom.sheetBottomEdgeBuffer;
ctrlPos.parametersGroupbox = [cx cy parametersGroupboxWidth parametersGroupboxHeight];

% correct some sizes
smallEditSize(1) = parametersEditSize(1) - browseButtonSize(1) - colDelta/3;
smallEditSize(2) = parametersEditSize(2);
parametersPopupSize(1) = parametersEditSize(1) - generateTRCCheckboxSize(1) - colDelta/3;

cx = col(1) + colWidth - 2*buildButtonSize(1);
cy = commonGeom.frameBottomEdgeBuffer;
ctrlPos.buildButton = [cx cy 2*buildButtonSize];

cx = col(1);
% checkboxes
ctrlPos.generatePPCApplicationCheckbox = [cx cy parametersCheckboxSize];
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.updateMakeFileCheckbox = [cx cy parametersCheckboxSize];
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.enableTRCFileFXPSupportCheckbox = [cx cy parametersCheckboxSize];
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.generateTRCCheckbox = [cx cy generateTRCCheckboxSize];

% TRC file hierachy
cx = cx + ctrlPos.generateTRCCheckbox(3) + colDelta/3;
ctrlPos.trcFileHierarchyPopup = [cx cy parametersPopupSize];

cx = col(1);
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.generateGlobalSymbolsCheckbox = [cx cy parametersCheckboxSize];
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.generateForIncrSubsystemsCheckbox = [cx cy parametersCheckboxSize];

% select DD CgUnit objects
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.DDCgUnitsListbox = [cx cy parametersEditSize(1) 4*parametersEditSize(2)];

cy = cy + 4*commonGeom.editHeight;
ctrlPos.enableDDCgUnitSelectionCheckbox = [cx cy parametersCheckboxSize];

% destination block
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.destinationBlockEdit = [cx cy parametersEditSize];

cy = cy + commonGeom.editHeight;
ctrlPos.destinationBlockLabel = [cx cy parametersLabelSize];

% select TargetLink subsystems
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.tlSubsystemListbox = [cx cy parametersEditSize(1) 4*parametersEditSize(2)];

cy = cy + 4*commonGeom.editHeight;
ctrlPos.tlSubsystemsLabel = [cx cy parametersLabelSize];

% destination directory
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.destinationDirectoryEdit = [cx cy smallEditSize];

cx = cx + ctrlPos.destinationDirectoryEdit(3) + colDelta/3;
ctrlPos.browseButton = [cx cy browseButtonSize];

cx = col(1);
cy = cy + commonGeom.editHeight;
ctrlPos.destinationDirectoryLabel = [cx cy parametersLabelSize];

% destination model
cy = cy + commonGeom.editHeight + rowDelta;
ctrlPos.destinationModelEdit = [cx cy parametersEditSize];

cy = cy + commonGeom.editHeight;
ctrlPos.destinationModelLabel = [cx cy parametersLabelSize];

width = ...
    parametersGroupboxWidth + ...
    2 * commonGeom.frameSideEdgeBuffer;
height = ...
    parametersGroupboxHeight + ...
    commonGeom.sheetBottomEdgeBuffer;

sheetDims = [width height];


%-------------------------------------------------------------------------------
% FcnCreate creates all controls of TargetLink Standalone Model Manager dialog.
%
% INPUT ARGUMENTS
%   options         dialog settings
%
% OUTPUT ARGUMENTS
%   dlgdata     dialog data
%-------------------------------------------------------------------------------
function dlgdata = FcnCreate(options)

dlgfig = figure( ...
    'DefaultUicontrolHorizontalAlign',   'left',...
    'Visible',                           'off',...
    'DefaultUicontrolUnits',             'pixels',...
    'DefaultUicontrolInterruptible',     'off',...
    'HandleVisibility',                  'off',...
    'Colormap',                          [],...
    'Toolbar',                           'none', ...
    'MenuBar',                           'none', ...
    'DockControls',                      'off', ...
    'NumberTitle',                       'off', ...
    'Name',                              'TargetLink Standalone Model Manager',...
    'IntegerHandle',                     'off',...
    'Interruptible',                     'off',...
    'Tag',                               'TargetLink Standalone Model Manager Dialog', ...
    'BusyAction',                        'queue',...
    'Resize',                            'off', ... 
    'Color',                             get(0,'DefaultuicontrolBackGroundColor'), ...
    'KeyPressFcn',                       ' ',...
    'CloseRequestFcn',                   'TLModelmanagerDlg(''manage'',gcbf,''Close'')');

% Construct common geometry constants.

commonGeom = ds_get_common_geometry;
set(dlgfig,...
    'DefaultUicontrolFontname', commonGeom.fontname,...
    'DefaultUicontrolFontsize', commonGeom.fontsize);

[sheetDims,ctrlPos] = FcnCtrlPositions(commonGeom);

parametersGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Parameters'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.parametersGroupbox);

Children.destinationModelLabel = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'String',             'Destination model name', ...
    'Style',              'text', ...
    'Position',           ctrlPos.destinationModelLabel);

Children.destinationModelEdit = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'String',             '', ...
    'BackGroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.destinationModelEdit);

Children.browseButton = uicontrol( ...
    'Parent',            parametersGroupbox, ...
    'Style',             'pushbutton', ...
    'String',            '  . . .  ', ...
    'Position',          ctrlPos.browseButton);

Children.destinationDirectoryLabel = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'String',             'Destination model directory', ...
    'Style',              'text', ...
    'Position',           ctrlPos.destinationDirectoryLabel);

Children.destinationDirectoryEdit = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'String',             '', ...
    'BackGroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.destinationDirectoryEdit);

Children.tlSubsystemsLabel = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'String',             'Select TargetLink subsystem(s) to be converted', ...
    'Style',              'text', ...
    'Position',           ctrlPos.tlSubsystemsLabel);

Children.tlSubsystemListbox = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'String',             ' ', ...
    'BackGroundColor',    'w', ...
    'Min',                0, ...
    'Max',                2, ...
    'Style',              'listbox', ...
    'Position',           ctrlPos.tlSubsystemListbox);

Children.destinationBlockLabel = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'String',             'Destination block for selected TargetLink subsystem', ...
    'Style',              'text', ...
    'Position',           ctrlPos.destinationBlockLabel);

Children.destinationBlockEdit = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'String',             '', ...
    'BackGroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.destinationBlockEdit);

Children.enableDDCgUnitSelectionCheckbox = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'Style',              'checkbox', ...
    'Value',              0, ...
    'String',             'Enable selection of the CodeGenerationUnit objects', ...
    'Position',           ctrlPos.enableDDCgUnitSelectionCheckbox);

Children.DDCgUnitsListbox = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'String',             ' ', ...
    'BackGroundColor',    'w', ...
    'Min',                0, ...
    'Max',                2, ...
    'Style',              'listbox', ...
    'Position',           ctrlPos.DDCgUnitsListbox);

Children.generateForIncrSubsystemsCheckbox = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'Style',              'checkbox', ...
    'Value',              0, ...
    'String',             'Include sub-items for code generation', ...
    'Position',           ctrlPos.generateForIncrSubsystemsCheckbox );

Children.generateGlobalSymbolsCheckbox = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'Style',              'checkbox', ...
    'Value',              0, ...
    'String',             'Create definitions for extern global interface variables', ...
    'Position',           ctrlPos.generateGlobalSymbolsCheckbox );

Children.generateTRCCheckbox = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'Style',              'checkbox', ...
    'Value',              1, ...
    'String',             'Generate TRC file, show hierarchy of', ...
    'Position',           ctrlPos.generateTRCCheckbox );

Children.trcFileHierarchyPopup = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'String',             {'Simulink subsystems'; 'generated functions'}, ...
    'Value',              1, ...
    'BackGroundColor',    'w', ...
    'Style',              'popupmenu', ...
    'Position',           ctrlPos.trcFileHierarchyPopup);

Children.enableTRCFileFXPSupportCheckbox = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'Style',              'checkbox', ...
    'Value',              1, ...
    'String',             'Enable TRC file Generator''s fix point data support', ...
    'Position',           ctrlPos.enableTRCFileFXPSupportCheckbox );

Children.updateMakeFileCheckbox = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'Style',              'checkbox', ...
    'Value',              1, ...
    'String',             'Update USR makefile for dSPACE RTI', ...
    'Position',           ctrlPos.updateMakeFileCheckbox );

Children.generatePPCApplicationCheckbox = uicontrol( ...
    'Parent',             parametersGroupbox, ...
    'Style',              'checkbox', ...
    'Value',              0, ...
    'String',             'Generate PPC application using dSPACE RTI', ...
    'Position',           ctrlPos.generatePPCApplicationCheckbox );

Children.buildButton = uicontrol( ...
    'Parent',            parametersGroupbox, ...
    'Style',             'pushbutton', ...
    'String',            '  Build  ', ...
    'Position',          ctrlPos.buildButton);

dlgdata.children = Children;
dlgdata.options = options;

offsets = [
    commonGeom.figSideEdgeBuffer
    commonGeom.figTopEdgeBuffer
    commonGeom.figSideEdgeBuffer
    commonGeom.bottomSheetOffset];

commonGeom.sheetPos = [
    offsets(1) + 1
    offsets(4) + 1
    sheetDims(1)
    sheetDims(2)
    ];
figPos = get(dlgfig,'Position');
figHeight = offsets(4) + ...  % bottom offset plus
    sheetDims(2) + ...        % height of sheet plus
    offsets(2) + ...          % top offset plus
    commonGeom.editHeight;    % status label
figWidth = offsets(1) + sheetDims(1) + offsets(3);

figPos(3:4) = [figWidth, figHeight];
screensize = get(0,'ScreenSize');
if figPos(1) + figPos(3) > screensize(3)
    figPos(1) = screensize(3) - figPos(3) - 20;
end
if figPos(2) + figPos(4) + 50 > screensize(4)
    figPos(2) = screensize(4) - figPos(4) - 50;
end

set(dlgfig,'Position',figPos);

% Create system buttons
dlgdata = FcnCreateSysButtons(dlgfig,dlgdata,commonGeom);

% set callbacks
children = struct2cell(dlgdata.children);
children = [children{:}];
fields = fieldnames(dlgdata.children);
for k = 1 : numel(children)
    if strcmp(get(children(k), 'Type'), 'uipushtool')
        set(children(k),'ClickedCallback',['TLModelmanagerDlg(''manage'',gcbf,''' fields{k} ''');']);
    else
        set(children(k),'callback',['TLModelmanagerDlg(''manage'',gcbf,''' fields{k} ''');']);
    end
end

FcnUpdate(dlgfig,dlgdata);

% make visible
set(dlgfig,'DefaultUicontrolVisible','on','Visible','on');


%-------------------------------------------------------------------------------
% FcnCreateSysButtons creates system buttons
%
% INPUT ARGUMENTS
%   dlgfig      handle of dialog figure
%   dlgdata     dialog data
%   commonGeom  common geometry like text height, ...
%
% OUTPUT ARGUMENTS
%   dlgdata     dialog data
%-------------------------------------------------------------------------------
function dlgdata = FcnCreateSysButtons(dlgfig, dlgdata, commonGeom)

figPos      = get(dlgfig,'Position');
sheetPos    = commonGeom.sheetPos;
width       = commonGeom.sysButtonWidth;
height      = commonGeom.sysButtonHeight;
buttonDelta = commonGeom.sysButtonDelta;
Children = dlgdata.children;

%******************************************************************************
% Place dSPACE logo
%******************************************************************************
cx = sheetPos(1)+ buttonDelta;
cy = commonGeom.figBottomEdgeBuffer + commonGeom.sysButton_SheetDelta;
ds_create_logo(dlgfig,cx,cy);

%******************************************************************************
% Place button.
%******************************************************************************
totalButtonWidth = (width * 2) + (buttonDelta * 1);
sheetEdge = sheetPos(1) + sheetPos(3);

cx = sheetEdge - totalButtonWidth;
cy = commonGeom.figBottomEdgeBuffer;

%******************************************************************************
% Place ok button.
%******************************************************************************
Children.Close = uicontrol( ...
    'Parent',            dlgfig,...
    'ToolTipString',     'Close dialog',...
    'String',            'Close',...
    'Horizontalalign',   'center',...
    'Position',          [cx cy width height]);


%******************************************************************************
% Place help button.
%******************************************************************************
cx = cx + width + buttonDelta;
Children.Help = uicontrol( ...
    'Parent',            dlgfig,...
    'ToolTipString',     'Open associated help document',...
    'String',            'Help',...
    'Enable',            'on',...
    'Horizontalalign',   'center',...
    'Position',          [cx cy width height]);


%******************************************************************************
% Place toolbar icons
%******************************************************************************
hToolbar = uitoolbar(dlgfig);
defaultColor = get(0,'DefaultUicontrolBackgroundColor');

%******************************************************************************
% Place Data Dictionary Manager button.
%******************************************************************************
cData = tl_get_icon('DDMan_20x20', 'BackgroundColor', defaultColor);
hPushbutton = uipushtool(hToolbar,'CData',cData, 'Separator', 'on');
set(hPushbutton, 'Enable', 'on', ...
    'ToolTipString', 'Open Data Dictionary Manager');
Children.Dsddman = hPushbutton;


%******************************************************************************
% Place Property Manager button.
%******************************************************************************
cData = tl_get_icon('PropMan_20x20', 'BackgroundColor', defaultColor);
hPushbutton = uipushtool(hToolbar,'CData',cData);
set(hPushbutton, 'Enable', 'on', ...
    'ToolTipString', 'Open Property Manager');
Children.Propman = hPushbutton;


%******************************************************************************
% Place Refresh button.
%******************************************************************************
cData = tl_get_icon('Refresh_20x20', 'BackgroundColor', defaultColor);
hPushbutton = uipushtool(hToolbar,'CData',cData);
set(hPushbutton, 'Enable', 'on', ...
    'ToolTipString', 'Refresh');
Children.Refresh = hPushbutton;


%******************************************************************************
% Place show message browser button.
%******************************************************************************
cData = tl_get_icon('MsgBrowser_20x20', 'BackgroundColor', defaultColor);
hPushbutton = uipushtool(hToolbar,'CData',cData);
set(hPushbutton, 'Enable', 'on', ...
    'ToolTipString', 'Open dSPACE Message Browser');
Children.ShowBrowser = hPushbutton;


%******************************************************************************
% Place status label.
%******************************************************************************
cx = commonGeom.figSideEdgeBuffer;
cy = commonGeom.sysButton_SheetDelta;
Children.StatusLabel = uicontrol( ...
    'Parent',            dlgfig,...
    'Style',             'text', ...
    'Horizontalalign',   'left',...
    'Position',          [cx cy figPos(3)-2*commonGeom.figSideEdgeBuffer commonGeom.textHeight]);

dlgdata.children = Children;


%-------------------------------------------------------------------------------
% FcnManageParametersPage manages option page.
%
% INPUT ARGUMENTS
%   dlgfig      figure handle
%   dlgdata     dialog data
%   action      depending on the field that has been edited
%
% OUTPUT ARGUMENTS
%   dlgdata     dialog data
%   bModified   flag = 1, if data has been modified, =0 otherwise
%-------------------------------------------------------------------------------
function FcnManageControls(dlgfig, dlgdata, action)

% default return value
bModified = false;
Children = dlgdata.children;
options = dlgdata.options;

switch action
    case 'destinationModelEdit'
        destinationModel = deblank(get(Children.destinationModelEdit,'String'));
        % remove the extension
        [path, options.destinationmodel] = fileparts(destinationModel);
        bModified = true;
        
    case 'browseButton'
        % open the directory browser
        directory = uigetdir('', 'Select a model directory');
        if ~isequal(directory,0)
            % a new directory has been selected
            options.destinationdirectory = directory;
            bModified = true;
        end
        
    case 'destinationDirectoryEdit'
        options.destinationdirectory = deblank(get(Children.destinationDirectoryEdit,'String'));
        bModified = true;
        
    case 'tlSubsystemListbox'
        bModified = true;
        
    case 'destinationBlockEdit'
        options.destinationblock = deblank(get(Children.destinationBlockEdit,'String'));
        bModified = true;
        
    case 'enableDDCgUnitSelectionCheckbox'
        options.enableddcgunitselection = get(Children.enableDDCgUnitSelectionCheckbox,'Value');
        bModified = true;
        
    case 'DDCgUnitsListbox'
        bModified = true;
        
    case 'generateForIncrSubsystemsCheckbox'
        options.generateforincrsubsystems = get(Children.generateForIncrSubsystemsCheckbox,'Value');
        bModified = true;
        
    case 'generateGlobalSymbolsCheckbox'
        options.generateglobalsymbols = get(Children.generateGlobalSymbolsCheckbox,'Value');
        bModified = true;
        
    case 'generateTRCCheckbox'
        options.generatetrc = get(Children.generateTRCCheckbox,'Value');
        bModified = true;
        
    case 'trcFileHierarchyPopup'
        trcFileValue = get(Children.trcFileHierarchyPopup, 'Value');
        trcFileStrings = get(Children.trcFileHierarchyPopup, 'String');
        options.trcfilehierarchy = trcFileStrings{trcFileValue};
        bModified = true;
        
    case 'enableTRCFileFXPSupportCheckbox'
        options.enabletrcfilefxpsupport = get(Children.enableTRCFileFXPSupportCheckbox,'Value');
        bModified = true;
        
    case 'updateMakeFileCheckbox'
        options.updatemakefile = get(Children.updateMakeFileCheckbox,'Value');
        bModified = true;
        
    case 'generatePPCApplicationCheckbox'
        options.generateppcapplication = get(Children.generatePPCApplicationCheckbox,'Value');
        bModified = true;
        
    case 'buildButton'
        FcnGenerateSFunction(options.model, options, Children);
        
    case {'Close','Cancel','CloseReq'}
        set(dlgfig,'Visible','off');
        delete(dlgfig);

    case 'Propman'
        tl_propman(bdroot(options.model));

    case 'Dsddman'
        dsddman;

    case 'Refresh'
        bModified = 1;
        
    case 'Help',
        % special case: online help uses old topic name
        tl_online_help('topic', 'TL_TL2RTI_DLG');

    case 'ShowBrowser'
        if isempty(ds_msgdlg('Show'))
            ds_msgdlg('Update');
        end

    otherwise
        error(['Invalid control ' action]);
        
end % switch(action)

if bModified
    dlgdata.options = options;
    FcnUpdate(dlgfig, dlgdata);
end


%-------------------------------------------------------------------------------
% FcnGenerateSFunction generates the stand-alone S-Function
%
% INPUT ARGUMENTS
%   hBlock      block handle
%   options     current block settings
%   Children    dialog controls
%
% OUTPUT ARGUMENTS
%   - / -
%-------------------------------------------------------------------------------
function FcnGenerateSFunction(hBlock, options, Children)

% get the inputs for the tl_tl2rti function
% source and destination model
if ~ds_isa(hBlock, 'slblock')
    [hBlock, msg] = tl_get_current_model;
    if isempty(hBlock)
        ds_error_msg(msg);
        return;
    end
end
srcModel      = bdroot(hBlock);
destModel     = options.destinationmodel;
destDirectory = options.destinationdirectory;

% check if destination directory exist
if ~exist(destDirectory,'dir'),
    ds_error_msg({...
        'The destination directory',...
        ['    ' destDirectory ],...
        'does not exist !'});
    return;
end

% check if destination model exist
destModelFullFileName = [destDirectory '' destModel '.mdl'];
if ~exist(destModelFullFileName,'file'),
    answer = ds_msgbox('Message',{ ...
        'The specified destination model',...
        ['      ' destModel], ...
        'does not exist in the destination directory.', ...
        'Thus it will be created as a copy of the source model', ...
        ['      ' get_param(srcModel,'Name')], ...
        '', ...
        'Do you wish to continue?',''}, ...
        'Title',   'Proceed and create new model?',...
        'Style',   'Question', ...
        'Button',  {'Continue','Abort'}, ...
        'Default', 'Continue', ...
        'Mode',    'modal');
    if strcmp(answer, 'Abort'),
        return;
    end
    % create the destination model
    srcFileName = get_param(srcModel, 'FileName');
    copyfile(srcFileName, destModelFullFileName);
end

% trc file options
trcFileHierarchy = 'subsystems';
generateTRC      = 'no';
fxpSupport       = 'no';
if options.generatetrc,
    generateTRC = 'yes';
    if strcmp(options.trcfilehierarchy, 'generated functions')
        trcFileHierarchy = 'functions';
    end
    if options.enabletrcfilefxpsupport,
        fxpSupport = 'yes';
    end
end
        
% get TL subsystems and corresponding destination blocks
selectedTlSubsystems = get(Children.tlSubsystemListbox,'Value');

% CodeGenerationUnits
if options.enableddcgunitselection
    DDCgUnits = get(Children.DDCgUnitsListbox,'String');
    selectedDDCgUnits = DDCgUnits(get(Children.DDCgUnitsListbox,'Value'));
else
    selectedDDCgUnits = '';
end

set(Children.StatusLabel,'String','Processing ...');

% Generate the stand-alone S-Function
tl_tl2rti('SrcModel'        ,srcModel,...
    'IncludeSubItems'       ,flag2str(options.generateforincrsubsystems),...
    'GenerateGlobalSymbols' ,flag2str(options.generateglobalsymbols),...
    'DestModel'             ,destModel,...
    'DestBlocks'            ,options.destinationblockList(selectedTlSubsystems),...
    'TLSubsystems'          ,options.availabletlsubsystemList(selectedTlSubsystems),...
    'DDCodeGenerationUnits' ,selectedDDCgUnits,...
    'GenerateTRC'           ,generateTRC,...
    'TRCFileHierarchy'      ,trcFileHierarchy,...
    'FixPointSupport'       ,fxpSupport,...
    'UpdateUsrMakeFile'     ,flag2str(options.updatemakefile),...
    'DestDirectory'         ,destDirectory,...
    'GeneratePPCApplication',flag2str(options.generateppcapplication));

set(Children.StatusLabel,'String','Standalone S-Fcn is generated.');


%-------------------------------------------------------------------------------
% FUNCTION DESCRIPTION
%   FcnUpdateParametersPage(dlgfig,dlgdata,pageNum)
%   Function to to update controls on parameters page: enable/disable controls,
%   write data to edit fields, highlight invalid/inconsistent data.
%   Function is called after FcnCreateParametersPage and by FcnManageParametersPage in
%   case the dialog has to be updated due to new data
%
% INPUT ARGUMENTS
%   pageNum     Number of page
%   dlgfig      Handle of dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     dialog data
%-------------------------------------------------------------------------------
function FcnUpdate(dlgfig, dlgdata)

options = dlgdata.options;
Children = dlgdata.children;
% get model name
if isempty(options.model) || ~ds_isa(options.model, 'slblock')
    bModel = false;
    % reset status line
    set(Children.StatusLabel, 'String', 'No open Simulink model found!');
else
    bModel = true;
    options.model = getfullname(bdroot(options.model));
    % reset status line
    set(Children.StatusLabel, 'String', ' ');
end

if strcmp(tl_get_blockset_mode, 'full-featured')
    IsFullVsON = 'on';
else
    IsFullVsON = 'inactive';
end
bRTIinstalled = exist('rtiver','file') == 2;

destinationModelEditCtrlStatus = struct('enable', IsFullVsON);
destinationDirectoryEditCtrlStatus = struct('enable', IsFullVsON);
tlSubsystemListboxCtrlStatus = struct('enable', IsFullVsON);
destinationBlockEditCtrlStatus = struct('enable', IsFullVsON);
enableDDCgUnitSelectionCheckboxCtrlStatus = struct('enable', IsFullVsON);
DDCgUnitsListboxCtrlStatus = struct('enable', IsFullVsON);
generateForIncrSubsystemsCheckboxCtrlStatus = struct('enable', IsFullVsON);
generateGlobalSymbolsCheckboxCtrlStatus = struct('enable', IsFullVsON);
generateTRCCheckboxCtrlStatus = struct('enable', IsFullVsON);
trcFileHierarchyPopupCtrlStatus = struct('enable', IsFullVsON, ...
    'string', {{'Simulink subsystems'; 'generated functions'}}, ...
    'value', 1);
enableTRCFileFXPSupportCheckboxCtrlStatus = struct('enable', IsFullVsON);
updateMakeFileCheckboxCtrlStatus = struct('enable', IsFullVsON);
generatePPCApplicationCheckboxCtrlStatus = struct('enable', flag2str(bRTIinstalled));
buildButtonCtrlStatus = struct('enable', IsFullVsON);

if bModel
    % get the list of all available tlSubsystems
    tlSubsystems = get_tlsubsystems(options.model);
else
    tlSubsystems = '';
end
if isempty(options.destinationmodel)
    % get default value
    defaultname = [options.model '_standalone'];
    if numel(defaultname) > namelengthmax
        defaultname = 'StandaloneModel';
    end
    options.destinationmodel = defaultname;
end
destinationModelEditCtrlStatus.string = options.destinationmodel;

if isempty(tlSubsystems),
    options.availabletlsubsystemList  = {''};
    options.destinationblockList  = {''};
    buildButtonCtrlStatus.enable = 'off';
else
    options.availabletlsubsystemList = cellstr(get_param(tlSubsystems,'Name')');
    for k = 1 : numel(tlSubsystems),
        options.destinationblockList{k} = [options.destinationmodel '/' options.availabletlsubsystemList{k}];
    end
end

% Get the list of all available DD CG Units
[tmp, ddCGUnitNames] = tl_get_ddcgunits;

selTLSubsystem = {options.availabletlsubsystemList{min(get(Children.tlSubsystemListbox, 'Value'), numel(options.availabletlsubsystemList))}};

if isempty(options.destinationdirectory)
    % get default value
    options.destinationdirectory = pwd;
end
destinationDirectoryEditCtrlStatus.string = options.destinationdirectory;
tlSubsystemListboxCtrlStatus.string = options.availabletlsubsystemList;

if numel(selTLSubsystem) == 1
    destinationBlockEditCtrlStatus.string = [destinationModelEditCtrlStatus.string '/' selTLSubsystem{1}];
else
    destinationBlockEditCtrlStatus.string = ' ';
    destinationBlockEditCtrlStatus.enable = 'inactive';
end

if isempty(ddCGUnitNames)
    enableDDCgUnitSelectionCheckboxCtrlStatus.enable = 'off';
    DDCgUnitsListboxCtrlStatus.enable = 'off';
    options.enableddcgunitselection = 0;
    DDCgUnitsListboxCtrlStatus.string = ' ';
else
    enableDDCgUnitSelectionCheckboxCtrlStatus.value = options.enableddcgunitselection;
    DDCgUnitsListboxCtrlStatus.string = ddCGUnitNames;
end
generateForIncrSubsystemsCheckboxCtrlStatus.value = options.generateforincrsubsystems;
generateGlobalSymbolsCheckboxCtrlStatus.value = options.generateglobalsymbols;
generateTRCCheckboxCtrlStatus.value = options.generatetrc;
if ~options.generatetrc
    trcFileHierarchyPopupCtrlStatus.enable = 'inactive';
end
trcFileHierarchyPopupCtrlStatus.value = find(strcmp(options.trcfilehierarchy, trcFileHierarchyPopupCtrlStatus.string));
enableTRCFileFXPSupportCheckboxCtrlStatus.value = options.enabletrcfilefxpsupport;
updateMakeFileCheckboxCtrlStatus.value = options.updatemakefile;
generatePPCApplicationCheckboxCtrlStatus.value = options.generateppcapplication;

dlgdata.options = options;

% set control status
ctrlsList = { ...
    'destinationModelEdit' ...
    'destinationDirectoryEdit' ...
    'destinationBlockEdit' ...
    'tlSubsystemListbox' ...
    'destinationModelEdit' ...
    'trcFileHierarchyPopup' ...
    'enableDDCgUnitSelectionCheckbox' ...
    'DDCgUnitsListbox' ...
    'generateTRCCheckbox' ...
    'enableTRCFileFXPSupportCheckbox' ...
    'updateMakeFileCheckbox' ...
    'generatePPCApplicationCheckbox' ...
    'generateGlobalSymbolsCheckbox' ...
    'buildButton'};

% write back control status of controls to the controls' UserData property
for ctrlsNo = 1:length(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end

% set control status of table parameter groupbox controls
TLSetCtrlsStatus(dlgfig, Children, ctrlsList)

% save user data
set(dlgfig,'UserData',dlgdata);

% move to front
figure(dlgfig);

% end of function FcnUpdateParametersPage


%-------------------------------------------------------------------------------
% FcnGetDefaultData gets default data set of model manager tool
%
% INPUT ARGUMENTS
%   - / -
%
% OUTPUT ARGUMENTS
%   options         default option set
%-------------------------------------------------------------------------------
function options = FcnGetDefaultData

options = struct( ...
    'revisionnumber',            4, ...
    'destinationmodel',          '', ...
    'destinationdirectory',      '', ...
    'destinationblock',          '', ...
    'availabletlsubsystemList',  {{''}}, ...
    'destinationblockList',      {{''}}, ...
    'trcfilehierarchy',          'Simulink subsystems', ...
    'enableddcgunitselection',   1, ...
    'generatetrc',               1, ...
    'enabletrcfilefxpsupport',   1, ...
    'updatemakefile',            1, ...
    'generateppcapplication',    0, ...
    'generateforincrsubsystems', 0, ...
    'generateglobalsymbols',     1 ...
    );
